<?php

declare(strict_types=1);

namespace App\CustHub\Service;

use App\CustHub\Constants\OpSchemeTypeConstants;
use App\CustHub\Mapper\ChOpSchemeMapper;
use App\CustHub\Model\ChCorpTag;
use App\CustHub\Model\ChOpSchemeRobot;
use App\CustHub\Model\ChSmartTag;
use Mine\Abstracts\AbstractService;
use Mine\Annotation\DeleteCache;
use Mine\Annotation\Transaction;
use Mine\MineModel;
use function Hyperf\Collection\collect;
use function Hyperf\Collection\data_get;

class ChOpSchemeService extends AbstractService
{
    public $mapper;

    public function __construct(ChOpSchemeMapper $mapper)
    {
        $this->mapper = $mapper;
    }

    public function list(array $data)
    {
        $type = data_get($data, 'type', OpSchemeTypeConstants::KEYWORD_TAG);

        $pageSize = data_get($data, 'page_size', MineModel::PAGE_SIZE);

        $corpTagIds =  data_get($data, 'corp_tag_ids');
        $smartTagIds = data_get($data, 'smart_tag_ids');
        $keyword = data_get($data, 'keyword');

        $paginate = $this->mapper->model::query()
            ->where('uid',$data['uid'])
            ->when(!empty($keyword),function ($query) use ($keyword){
                $query->whereRaw("JSON_SEARCH(cfg, 'one', '%{$keyword}%', NULL, '$.keywords') IS NOT NULL");
            })
            ->when(!empty($corpTagIds),function ($query) use ($corpTagIds){
                $query->whereRaw("JSON_CONTAINS(`cfg`, '{$corpTagIds}', '$.corp_tag_ids')");
            })
            ->when(!empty($smartTagIds),function ($query) use ($smartTagIds){
                $query->whereRaw("JSON_CONTAINS(`cfg`, '{$smartTagIds}', '$.smart_tag_ids')");
            })
            ->orderBy('created_at','desc')
            ->paginate((int)$pageSize);

        $paginate = $this->mapper->setPaginate($paginate);

        $items = collect($paginate['items']);

        if($type == OpSchemeTypeConstants::KEYWORD_TAG){
            $corpTagIds = $items->flatMap(function ($item){
                return $item['cfg']['corp_tag_ids'] ?? [];
            })->unique()->toArray();

            $smartTagIds = $items->flatMap(function ($item){
                return $item['cfg']['smart_tag_ids'] ?? [];
            })->unique()->toArray();

            //查询企业标签
            $corpTagList = ChCorpTag::query()
                ->whereIn('id',$corpTagIds)
                ->pluck('name','id')
                ->toArray();

            //查询智能标签
            $smartTagList = ChSmartTag::query()
                ->whereIn('id',$smartTagIds)
                ->pluck('name','id')
                ->toArray();

            $items = $items->map(function ($item) use ($corpTagList,$smartTagList){
                $cfg = $item['cfg'];
                if(!empty($cfg['corp_tag_ids'])){
                    foreach ($cfg['corp_tag_ids'] as $corpTagId){
                        if(isset($corpTagList[$corpTagId])){
                            $cfg['corp_tags'][] = [
                                'id' => $corpTagId,
                                'name' => $corpTagList[$corpTagId]
                            ];
                        }
                    }
                }

                if(!empty($cfg['smart_tag_ids'])){
                    foreach ($cfg['smart_tag_ids'] as $corpTagId){
                        if(isset($smartTagList[$corpTagId])){
                            $cfg['smart_tags'][] = [
                                'id' => $corpTagId,
                                'name' => $smartTagList[$corpTagId]
                            ];
                        }
                    }
                }
                $item['cfg'] = $cfg;
                return $item;
            });
            $paginate['items'] = $items;
        }

        return $paginate;
    }

    public function save(array $data):mixed
    {
        $cfg = data_get($data,'cfg');
        if(!empty($cfg)){
            $data['cfg'] = json_decode($data['cfg'],true);
        }
        return $this->mapper->save($data);
    }

    #[DeleteCache("ch_op_scheme:id_#{id}")]
    public function update(mixed $id,array $data):bool
    {
        $data['cfg'] = json_decode($data['cfg'],true);
        return $this->mapper->update($id,$data);
    }

    #[DeleteCache("ch_op_scheme:id_#{id}"),Transaction]
    public function deleteScheme(mixed $id): bool
    {
        $scheme = $this->mapper->model::query()->find($id);
        if ($scheme) {
            ChOpSchemeRobot::query()->where('scheme_id',$id)->delete();
            $scheme->delete();
        }
        return true;
    }



    public function keywordTagScheme()
    {

    }
}